package com.cbw.firegame.member.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cbw.common.vo.MemberEntity;
import com.cbw.firegame.member.service.MemberService;
import com.cbw.firegame.member.vo.LoginVo;
import com.cbw.firegame.member.vo.refreshVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    MemberService memberService;

    @PostMapping("/tologin")
    public String tologin(LoginVo vo , RedirectAttributes redirectAttributes, HttpSession session){

        String username = vo.getUsername();
        String password = vo.getPassword();
        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<MemberEntity>();
        wrapper.and(w->{
            w.eq("username",username).or().eq("mobile",username);
        });
        MemberEntity entity = memberService.getOne(wrapper);
        if (entity==null){

            redirectAttributes.addFlashAttribute("error","用户不存在");
            return "redirect:http://localhost:9100/login";
        }else {

            if (entity.getStatus()==0){
                redirectAttributes.addFlashAttribute("error","用户被禁用");
                return "redirect:http://localhost:9100/login";
            }



            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, passwordDb);
            if (matches){
//                redirectAttributes.addFlashAttribute("user",entity);
                session.setAttribute("loginUser",entity);

                return "redirect:http://localhost:9300";
            }else {
                redirectAttributes.addFlashAttribute("error","用户名或密码错误");
                return "redirect:http://localhost:9100/login";
            }

        }


    }
//    public MemberEntity oauth2login(refreshVo vo) throws Exception {
//     MemberEntity entity=memberService.login(vo);
//    return entity;
//    }




    @RequestMapping("/quit")
    public String quit(HttpServletRequest request,HttpSession session){
        session.removeAttribute("loginUser");
        return "redirect:http://localhost:9300";
    }








}
